package com.lcredu.springbootusersys.controller;

import com.lcredu.springbootusersys.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@Slf4j
public class UploadController {

    @GetMapping("/upload.html")
    public String showUploadForm() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String handleUpload(@RequestParam("name") String name,
                               @RequestParam("email") String email,
                               @RequestParam("age") Integer age,
                               @RequestParam("job") String job,
                               @RequestParam("header") MultipartFile header,
                               @RequestParam("photos") MultipartFile[] photos) throws IOException {
        log.info("收到信息name={} email={} age={} job={} header={} photos={}", name, email, age, job, header.getSize(), photos.length);

        //获取文件名字
        String fileName = header.getOriginalFilename();
        //获取真实的项目路径
        //path=/D:/Code/JavaCode/Spring/springboot/springboot-usersys/target/classes/
        String path = ResourceUtils.getURL("classpath:").getPath();
        log.info("path={}", path);
        //创造文件目录与文件 \static\images
        File directory = new File(path + File.separator + FileUtil.getDirect());
        //判断目录是否存在
        if (!directory.exists()) {
            directory.mkdirs();
        }
        //在这里我们可以取名保证文件覆盖
        String key = UUID.randomUUID() + "_" + System.currentTimeMillis() + "_";
        File file = new File(directory + File.separator + key + fileName);
        //传入数据
        header.transferTo(file);

        //数组传入
        if (photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    key = UUID.randomUUID() + "_" + System.currentTimeMillis() + "_";
                    String filename = photo.getOriginalFilename();
                    File photoFile = new File(File.separator +
                            directory + File.separator + key + filename);
                    photo.transferTo(photoFile);
                }
            }
        }


        // 处理上传逻辑
        return "success";
    }

}
